//
//  XQHomeViewController.swift
//  XiaoQiQiaoSwift
//
//  Created by tech-lab on 2016/11/24.
//  Copyright © 2016年 校企桥. All rights reserved.
//
import Alamofire
import AlamofireObjectMapper
import ObjectMapper
import SwiftyJSON
import Foundation
import UIKit


class XQHomeViewController: XQBaseViewController,UITableViewDelegate,UITableViewDataSource {

    private let XQHomeFirstTableViewCellID  = "XQHomeFirstTableViewCellID"
    private let XQHomeSecondTableViewCellID = "XQHomeSecondTableViewCellID"
    private let XQHomeThreeTableViewCellID = "XQHomeThreeTableViewCellID"
    private let XQHomeFourTableViewCellID = "XQHomeFourTableViewCellID"
    private let XQHomeFiveTableViewCellID = "XQHomeFiveTableViewCellID"

    private  var bannerView: LLCycleScrollView!

    private  var tableView = UITableView()
    
    private  var urlArray = NSMutableArray()
    private  var imgurlArray = NSMutableArray()
    
    private var homeAllMode:XQHomeMode?

    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationItem.title = "校企桥"
        // Do any additional setup after loading the view.
        self.navigationItem.leftBarButtonItem = nil
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

   private func InitlunBoView(){
        self.bannerView = LLCycleScrollView.llCycleScrollViewWithFrame(CGRect.init(x: 0, y: 0, width: SCREEN_WIDTH, height: 150))
        bannerView.scrollDirection = .horizontal
        bannerView.autoScrollTimeInterval = 3.0
        bannerView.placeHolderImage = UIImage.init(named: "homeheader")
        bannerView.coverImage = UIImage.init(named: "homeheader")
    
    }
    
    override func setRootView() {
     
        InitlunBoView()

        tableView = UITableView.init(frame: CGRect.zero, style: .grouped)
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.showsVerticalScrollIndicator = false
        self.view.addSubview(tableView)
        
        tableView.snp.makeConstraints { (make) in
            make.left.equalTo(self.view.snp.left)
            make.right.equalTo(self.view.snp.right)
            make.top.equalTo(self.view.snp.top)
            make.bottom.equalTo(self.view.snp.bottom)
        }
        
        tableView.tableHeaderView = bannerView
        
        self.tableView.register(XQHomeFirstTableViewCell.self, forCellReuseIdentifier: XQHomeFirstTableViewCellID)
        self.tableView.register(XQHomeSecondTableViewCell.self, forCellReuseIdentifier: XQHomeSecondTableViewCellID)
        self.tableView .register(XQHomeThreeTableViewCell.self, forCellReuseIdentifier: XQHomeThreeTableViewCellID)
        self.tableView .register(XQHomeFourTableViewCell.self, forCellReuseIdentifier: XQHomeFourTableViewCellID)
        self.tableView .register(XQHomeFiveTableViewCell.self, forCellReuseIdentifier: XQHomeFiveTableViewCellID)
        homeBanenrData()
        homeContentData()
        
    }
    
   private  func homeBanenrData() {
        
        let urlstr = MTBaseURL.appending("NewVerHome/index.json")
        
       // let parameters = NSDictionary.init(dictionary: ["":"","":"","":""])
        
    Alamofire.request(urlstr).responseJSON { (response) in
          
            self.urlArray = NSMutableArray.init()
            self.imgurlArray = NSMutableArray.init()
            
            let result = JSON.init(data: response.data!)
            
            let mainArray = result["main"].arrayValue;
            
            for subJson:JSON in mainArray {
                //Do something you want
                //NSLog("++++%@", subJson["img"].stringValue)
                //NSLog("----%@", subJson["uri"].stringValue)
                let img = subJson["img"].stringValue
                let uri = subJson["uri"].stringValue
                
                self.urlArray .add(uri)
                self.imgurlArray .add(img)
                
            }
            
            let imgurl:[NSString] = NSArray.init(array: self.imgurlArray) as! [NSString];

            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .seconds(2)) {
                self.bannerView.imagePaths = imgurl as Array<String>
            }
        }
    }
    
    
    
    private func homeContentData() {
        
        let urlstr = MTBaseURL.appending("NewVerHome/homeMain.json")
        
        Alamofire.request(urlstr).responseObject { (response: DataResponse<XQHomeMode>) in
            print(response)
            self.homeAllMode = response.result.value
            self.tableView.reloadData()
        }
    }
    
    
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 5
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 4 {
            if ((self.homeAllMode?.course) != nil) {
                return (self.homeAllMode?.course?.count)!
            }
            return 0
        }else{
            return 1
            
        }
        
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        var sectionHeight = 0 
        
        switch section {
        case 0:
            sectionHeight = Int(0.1)
            break
        case 1:
            sectionHeight = Int(5)
            break
        case 2:
            sectionHeight = Int(5)
            break
        case 3:
            sectionHeight = Int(30)
            break
        case 4:
            sectionHeight = Int(30)
            break
        default:
            break
        }
        return  CGFloat(sectionHeight)
        
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.1
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath:
        IndexPath) -> CGFloat {
        var rowHeight = 0
        switch indexPath.section {
        case 0:
            rowHeight = Int(SCREEN_WIDTH/2)
            break
        case 1:
            rowHeight = 40
            break
        case 2:
            rowHeight = 80
            break
        case 3:
            rowHeight = 120
            break
        case 4:
            rowHeight = 80
            break
        default:
            break
        }
        return CGFloat(rowHeight)
    }
    
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        if section == 3 {
            return "为您推荐"
        }else if section == 4{
            return "精彩课程"
        }else{
            return ""
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if indexPath.section == 0 {
            let firstCell:XQHomeFirstTableViewCell = tableView.dequeueReusableCell(withIdentifier: XQHomeFirstTableViewCellID) as!XQHomeFirstTableViewCell
//            if firstCell == nil {
//                firstCell = XQHomeFirstTableViewCell.init(style: .default, reuseIdentifier: XQHomeFirstTableViewCellID)
//            }
            firstCell.homeself = self
            return firstCell
            
        }else if indexPath.section == 1 {
            let secondCell = tableView.dequeueReusableCell(withIdentifier: XQHomeSecondTableViewCellID) as!XQHomeSecondTableViewCell
//            if secondCell == nil {
//                secondCell = XQHomeSecondTableViewCell.init(style: .default, reuseIdentifier: XQHomeSecondTableViewCellID)
//            }
            if ((homeAllMode?.top) != nil) {
                secondCell.titleLabel.text = homeAllMode?.top?.title
            }
            return secondCell
            
        }else if indexPath.section == 2 {
            let threeCell = tableView.dequeueReusableCell(withIdentifier: XQHomeThreeTableViewCellID) as!XQHomeThreeTableViewCell
            return threeCell
        }else if indexPath.section == 3{
            let fourCell = tableView.dequeueReusableCell(withIdentifier: XQHomeFourTableViewCellID) as!XQHomeFourTableViewCell
            
            if ((homeAllMode?.jobs) != nil) {
                fourCell.dataArray = (homeAllMode?.jobs)!
                fourCell.collectionView .reloadData()
            }
            fourCell.homeself = self
            return fourCell
            
        }else{
            let fiveCell = tableView.dequeueReusableCell(withIdentifier: XQHomeFiveTableViewCellID) as!XQHomeFiveTableViewCell
            fiveCell.courseMode = (homeAllMode?.course?[indexPath.row])!
            return fiveCell
        }
        
      
    }
    
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        if indexPath.section == 1 {
            if ((homeAllMode?.top?.url) != nil) {
                let url = URL.init(string: (homeAllMode?.top?.url)!)
                UIApplication.shared .openURL(url!)
            }
        }else if indexPath.section == 4{
            
            let  detailVc =  XQCourseDetailViewController()
            let courseMode = self.homeAllMode?.course?[indexPath.row]
            detailVc.cid = (courseMode?.id)!
            detailVc.type = (courseMode?.type)!
            detailVc.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(detailVc, animated: true)

            
        }
    }
    
    
    
}
